import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart' hide Response;

import '../api/tokenApi.dart';
import '../config/dioConfig.dart';
import '../enum/token.dart';
import '../tools/commons.dart';

class DioLogInterceptor extends Interceptor {
  //请求前
  @override
  Future<void> onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    if (options.headers["token"] == null) {
      options.headers["token"] = await CommonUtils.getToken(Token.AccessToken);
    }
    print("请求地址：${options.uri}");
    print("请求头：${options.headers}");
    print("请求参数：${options.data}");
    super.onRequest(options, handler);
  }

  //请求完成
  @override
  Future<void> onResponse(
      Response response, ResponseInterceptorHandler handler) async {
    // print("响应数据：${response.data}");
    var resData = response.data["data"];
    var resCode = response.data["code"];
    var resMsg = response.data["message"];

    try {
      if (resData != null && resData is Map) {
        //从响应设置accessToken
        if (resData.containsKey("accessToken")) {
          CommonUtils.saveToken(Token.AccessToken, resData["accessToken"]);
          response.requestOptions.headers["token"] = resData["accessToken"];
        }

        //从响应设置refreshToken
        if (resData.containsKey("refreshToken")) {
          CommonUtils.saveToken(Token.RefreshToken, resData["refreshToken"]);
        }
      }
    } finally {
      //判断响应状态码
      if (resCode == 0) {
        handler.next(response);
      } else {
        if (resCode == 40101) {
          //无权限,跳转首页
          CommonUtils.showToast(resMsg);
        } else if (resCode == 40102 &&
            !await isRefreshRequest(response.requestOptions)) {
          //刷新token
          print("accessToken过期，自动刷新token");
          var isSuccessful = await refreshToken();
          print("重新刷新成功状态:$isSuccessful");
          if (isSuccessful) {
            //重新请求
            response.requestOptions.headers["token"] =
                CommonUtils.getToken(Token.AccessToken);
            //获取上一个请求的方法
            var method = response.requestOptions.method;
            return await HttpManager.getInstance().request(
              response.requestOptions.path,
              method: method,
              params: response.requestOptions.data,
            );
          } else {
            print("刷新token失败，跳转到登录页面");
            CommonUtils.showToast("登陆失效");
            //跳转到登录页面
            // await Get.offAllNamed('/');
          }
        } else if (resCode == 40100) {
          Get.snackbar("提示！", "未登录!",
              snackPosition: SnackPosition.TOP,
              icon: Icon(Icons.error),
              mainButton: TextButton(
                  onPressed: () {
                    // Get.back();
                    // Get.offAllNamed('/');
                    Get.toNamed("/login");
                  },
                  child: Text("点击登录")));
        } else {
          CommonUtils.showToast(resMsg);
        }
      }
    }
  }
}
